package com.wwy.user.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.common.domain.CommonResult;
import com.common.domain.ResultCode;
import com.common.enums.GlobalErrorCodeConstants;
import com.common.utils.MobileUtil;
import com.common.utils.NoteSampleUtil;
import com.wwy.user.config.redis.RedisService;
import com.wwy.user.constans.StringConstans;
import com.wwy.user.mapper.UserMapper;
import com.wwy.user.module.entity.User;
import com.wwy.user.module.vo.user.UserLogin;
import com.wwy.user.module.vo.user.UserSaveVo;
import com.wwy.user.service.UserLoginService;
import com.wwy.user.utils.PasswordBCrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 王伟羽
 * @program: almighty
 * @description: 用户登录服务
 * @create: 2024/11/05
 */

@Slf4j
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Resource
    private RedisService redisService;

    @Resource
    private UserMapper userMapper;



    @Override
    public CommonResult login(UserLogin userLogin) {
        String userId = null;
        try {
            //用户使用验证码登录
            if (userLogin.getType().equals(0L)) {
                String s = redisService.getStr(StringConstans.USER_TOKEN,userLogin.getUsername());
                if (StringUtils.isEmpty(s)) {
                    return CommonResult.error(ResultCode.NOTEINVALID.getCode(), ResultCode.NOTEINVALID.getMessage());
                }
                if (s.equals(userLogin.getNodeInfo())) {
                    //生成token
                    List<User> userList = userMapper.selectList(userLogin);
                    if (CollectionUtils.isNotEmpty(userList)) {
                        userId = userList.get(0).getId();
                        StpUtil.login(userId);
                    }
                } else {
                    return CommonResult.error(401, "验证码错误!");
                }
            }
            if (userLogin.getType().equals(1L)) {
                List<User> userList = userMapper.selectList(userLogin);
                if (CollectionUtils.isEmpty(userList)) {
                    throw new RuntimeException("用户不存在");
                }
                //判断密码是否相同
                User user = userList.get(0);
                if(PasswordBCrypt.checkPassword(userLogin.getPassword(),user.getPassword())){
                    userId = userList.get(0).getId();
                    StpUtil.login(userId);
                }else{
                    return CommonResult.error(10086,"账号密码错误！");
                }
            }
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return CommonResult.success(tokenInfo);
        } catch (Exception e) {
            return CommonResult.error(400, "服务器正忙,请稍后再试");
        }
    }

    @Override
    public CommonResult userRegister(UserLogin user) {
        //前端进行校验之后 后台再次判断用户填写手机号是否符合规范
        if (StringUtils.isEmpty(user.getUsername())) {
            return CommonResult.error(GlobalErrorCodeConstants.SJHCW);
        }
        if (!MobileUtil.checkPhone(user.getUsername())) {
            return CommonResult.error(GlobalErrorCodeConstants.SJH_NO_SUPPORT);
        }
        //判断用户手机号是否已被注册
        List<User> userList = userMapper.selectList(user);
        if (CollectionUtils.isNotEmpty(userList)) {
            return CommonResult.error(GlobalErrorCodeConstants.YHYBZC);
        }
        //随机生成验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
//        try {
//            NoteSampleUtil.sendNode(user.getUsername(), code);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("发送短信失败！");
//            return CommonResult.error(GlobalErrorCodeConstants.LOCKED);
//        }
        //将其生成的验证码存入到redis缓存中
        redisService.set(StringConstans.USER_CODE,user.getUsername(), code,60L);
        return CommonResult.success(true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult register(UserSaveVo user) {
        User userLogin = new User();
        //激活用户
        String s = redisService.getStr(StringConstans.USER_CODE,user.getUsername());
        if (StringUtils.isEmpty(s)) {
            return CommonResult.error(GlobalErrorCodeConstants.NOTEINVALID);
        }
        //如果验证码正确则进行注册并对其输入密码进行加密
        if (s.equals(user.getNodeCode())) {
            //将密码进行加密操作
            String encodePassword = "kunkun123456";
            //设置默认头像
            userLogin.setIcon("https://imgessl.kugou.com/stdmusic/20190621/20190621030512241379.jpg");
            //设置默认昵称
            userLogin.setNickname("坤坤点评" + UUID.randomUUID());
            //设置为普通用户
            userLogin.setUserStatus(0);
            userLogin.setSex(1);
            userLogin.setPhone(user.getPhone());
            userLogin.setUsername(user.getPhone());
            userLogin.setPassword(PasswordBCrypt.hashPasswordBCrypt(encodePassword));
            userMapper.insert(userLogin);
            //插入成功存入缓存并生成token返回前端
            String userId = userLogin.getId();
            StpUtil.login(userId);
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            redisService.set(StringConstans.USER_TOKEN,userId, JSONObject.toJSONString(tokenInfo),3600L);
            return CommonResult.success(tokenInfo);
        } else {
            return CommonResult.error(GlobalErrorCodeConstants.YZM_ERROR);
        }
    }

    @Override
    public CommonResult sendNode(String username) {
        //前端进行校验之后 后台再次判断用户填写手机号是否符合规范
        if (StringUtils.isEmpty(username)) {
            return CommonResult.error(GlobalErrorCodeConstants.SJHCW);
        }
        if (!MobileUtil.checkPhone(username)) {
            return CommonResult.error(GlobalErrorCodeConstants.SJH_NO_SUPPORT);
        }
        //随机生成验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        try {
            NoteSampleUtil.sendNode(username, code);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送短信失败！");
            return CommonResult.error(GlobalErrorCodeConstants.LOCKED);
        }
        //将其生成的验证码存入到redis缓存中
        redisService.set(StringConstans.USER_CODE,username, code, 60);
        return CommonResult.success(true);
    }
}
